package com.fang.fen.blog.user.controller;

import com.fang.fen.blog.common.exception.ApplicationException;
import com.fang.fen.blog.user.domain.User;
import com.fang.fen.blog.user.dto.UserDTO;
import com.fang.fen.blog.user.exception.NameRepeatException;
import com.fang.fen.blog.user.service.UserService;
import com.fang.fen.blog.user.vo.UserVO;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

@RestController
@RequestMapping("/user")
public class UserController {


    @Autowired
    private UserService userService;


    @PostMapping(path = "/")
    public void create(@RequestBody UserDTO userDTO) throws ApplicationException{
        if(userService.create(userDTO) == 0) {
            throw new NameRepeatException();
        }
    }

    @GetMapping(path = "/{pageIndex}/{pageSize}")
    public PageInfo<User> page(@PathVariable("pageIndex") int pageIndex, @PathVariable("pageSize") int pageSize,User user) {

        List<Integer> list = new ArrayList<>();
//        int i = 0;
//        while (pageSize > 0) {
//            list.add(i++);
//        }

        Object bigGate = new Object();
        Object smallGate = new Object();
        new Thread(new Runnable() {
            @Override
            public void run() {
                String name = Thread.currentThread().getName();
                synchronized (bigGate){
                    System.out.println(name + ":我把大门给锁了...然后我休息一下...");
                    try {
                        Thread.sleep(200);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    System.out.println(name + ":我现在要进入小门.....");
                    synchronized (smallGate){
                        System.out.println(name + ":我永远都进不来啊.....");
                    }

                }
            }
        },"小明").start();
        new Thread(new Runnable() {
            @Override
            public void run() {
                String name = Thread.currentThread().getName();
                synchronized (smallGate){
                    System.out.println(name + ":我把小门给锁了...然后我休息一下...");
                    try {
                        Thread.sleep(200);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    System.out.println(name + ":我现在要进入大门.....");
                    synchronized (bigGate){
                        System.out.println(name + ":我永远都进不来啊.....");
                    }

                }
            }
        },"小红").start();
        return userService.page(pageIndex, pageSize, user);
    }

}
